//
//  LCOAuthModel.swift
//  SinaWeiBo
//
//  Created by mac on 16/12/4.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit

//AccessToKen的model
class LCOAuthModel: NSObject,NSCoding{
    
    //1access_token
    var access_token:String?
    //2	access_token的生命周期（是创建access——token开始到过期的秒数）
    var expires_in: TimeInterval = 0 {
        didSet{//在expires赋值的时候就计算出过期日期
            expores_date = Date().addingTimeInterval(expires_in)
        }
    }
    //定义一个过期日期
    var expores_date: Date?
    //3 授权用户的UID
    var uid: Int64 = 0
    //4 用户图片
    var avatar_large: String?
    //5 用户名称
    var name: String?
    //6 微博id
    var id: Int64 = 0

    //定义构造函数
    init(dic: [String:Any]) {
        super.init()
        setValuesForKeys(dic)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    //归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expores_date, forKey: "expores_date")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(id, forKey: "id")
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as! String?
        expores_date = aDecoder.decodeObject(forKey: "expores_date") as! Date?
//        uid = aDecoder.decodeObject(forKey: "uid") as? Int64
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as! String?
        name = aDecoder.decodeObject(forKey: "name") as! String?
    }
    //保存用户对象
    func saveUserAccount(){
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        //  归档操作
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //读取本地归档的用户信息
    class func loadUserAccount() -> LCOAuthModel? {
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: path)
        
        return userAccount as? LCOAuthModel
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
